from flask import Blueprint, render_template, request, send_file
from applications.models import UrlModel
from sqlalchemy import or_
from applications.extensions import db

spider_index = Blueprint('spiderIndex', __name__, url_prefix='/spider/index')


@spider_index.get('/')
def index():
    return render_template('spider/index/index.html')


@spider_index.route('/result/<int:res_id>')
def get_single_result(res_id):
    result = UrlModel.query.get(res_id)
    return render_template('spider/compoment/singleResult.html', result=result)


@spider_index.route('/result/html', methods=['POST', 'GET'])
def get_html():
    content_href=request.get_json('content_href')
    return render_template(content_href)


@spider_index.route('/search')
def get_search_res():
    key_word = request.args.get("keyWord")
    res = UrlModel.query.filter(or_(UrlModel.title.contains(key_word), UrlModel.details.contains(key_word),
                                    UrlModel.remark.contains(key_word))).order_by(
        db.text("-time"))
    results = []
    for r in res:
        if r.enable == 1 and r.finish == 1:
            results.append(r)
    return render_template("spider/compoment/searchResult.html", results=results)
